#include "RequestHandlerHolder.h"

namespace OCPP
{
	RequestHandlerHolder::RequestHandlerHolder(RequestHandler* handler)
		: mHandler(handler) {}

	// Disconnect the handler to allow it to be destroyed
	void RequestHandlerHolder::disconnectHandler()
	{
		// write lock - must wait for all requests to finish
		CORE_LOCK_RW_MUTEX_WRITE(mRWMutex);
		mHandler = 0;
	}

	/** Get handler pointer - note, only use this for == comparison or similar,
		do not attempt to call it as it is not thread safe.
	*/
	RequestHandler* RequestHandlerHolder::getHandler() { return mHandler; }

	/** Process a request if possible.
	@return Valid response if processed, null otherwise
	*/
	Response* RequestHandlerHolder::handleRequest(const Request* req, const WorkQueue* srcQ)
	{
		// Read mutex so that multiple requests can be processed by the
		// same handler in parallel if required
		CORE_LOCK_RW_MUTEX_READ(mRWMutex);
		Response* response = 0;
		if (mHandler)
		{
			if (mHandler->canHandleRequest(req, srcQ))
			{
				response = mHandler->handleRequest(req, srcQ);
			}
		}
		return response;
	}
}